<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('introduce') : $t('introduce')" width="800px" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
      <el-row>
        <el-col :span="12">
          <el-form-item size='small' label="所在猪舍" prop="houseId">
            <el-select v-model="dataForm.houseId" @change="house_change" placeholder="猪舍">
              <el-option
                  v-for="(house, house_id) in houses"
                  :key="house_id"
                  :label="house.name"
                  :value="house_id">
              </el-option>
            </el-select>
            <!-- <House placeholder="猪舍" v-model="dataForm.houseId" @change="house_change"></House> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="栏位" prop="grid">
            <el-select size='mini' style="width: 90px" v-model="dataForm.grid.row" placeholder="行">
              <el-option
                v-for="item in rows"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select size='mini' style="width: 90px" v-model="dataForm.grid.column" placeholder="列">
              <el-option
                v-for="item in columns"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-button slot="append">{{dataForm.grid.name}}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item size='small' label="耳号" prop="earmark">
            <el-input v-model="dataForm.earmark" placeholder="耳号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="性别" prop="gender">
            <RenSelect dictType="gender" placeholder="性别" v-model="dataForm.gender"></RenSelect>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item size='small' label="进场类型" prop="sources">
            <RenSelect dictType="source" placeholder="进场类型" v-model="dataForm.sources"></RenSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="进场日期" prop="inDate">
            <el-date-picker
              v-model="dataForm.inDate"
              align="right"
              type="date"
              placeholder="进场日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item size='small' label="出生日期" prop="birthDate">
            <el-date-picker
              v-model="dataForm.birthDate"
              align="right"
              type="date"
              placeholder="出生日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="血统" prop="pedigree">
            <el-input v-model="dataForm.pedigree" placeholder="血统"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item size='small' label="品种" prop="breed">
            <RenSelect dictType="breed" placeholder="品种" v-model="dataForm.breed"></RenSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="品系" prop="strain">
            <RenSelect dictType="strain" placeholder="品系" v-model="dataForm.strain"></RenSelect>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" v-show="dataForm.gender!='0'">
          <el-form-item size='small' label="生产状态" prop="state">
            <RenSelect dictType="pig_status" placeholder="" v-model="dataForm.state"></RenSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="dataForm.gender=='0'">
          <el-form-item size='small' label="生产状态" prop="state">
            <RenSelect dictType="boar_status" placeholder="" v-model="dataForm.state"></RenSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="操作人" prop="operator">
            <UserSelect v-model="dataForm.operator"></UserSelect>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" v-show="dataForm.gender=='1'">
          <el-form-item size='small' label="胎次" prop="parity">
            <el-input v-model="dataForm.parity" placeholder="胎次"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item size='small' label="备注" prop="remark">
        <el-input type="textarea" :rows="2" v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
      <Grid v-if="dataForm.houseId" alone="1" v-on:gridSelect="gridSelect" :pig="dataForm" :house_id="dataForm.houseId"></Grid>
    </el-form>
    <template slot="footer">
      <el-divider></el-divider>
      <el-row>
        <el-col :span="4">
          <el-button @click="inBtnClick()">{{ $t('batchImport') }}</el-button>
        </el-col>
        <el-col :span="4">
          <el-checkbox label="连续录入" v-model="continues"></el-checkbox>
        </el-col>
        <el-col :span="16">
          <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
          <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>

</template>

<script>/* eslint-disable */
import debounce from 'lodash/debounce'
import house from '../../basic/house.vue';
export default {
  components: { house },
  data () {
    return {
      rows: [],
      columns: [],
      visible: false,
      earmarkRequired: true,
      continues: true,
      dataForm: {
        id: '',
        houseId: '',
        earmark: '',
        gender: '',
        grid: {
          row: '',
          column: ''
        },
        sources: '',
        state: '',
        inDate: '',
        parity: '',
        birthDate: '',
        age: '',
        birthWeight: '',
        siblings: '',
        breed: '',
        strain: '',
        pedigree: '',
        father: '',
        fatherIndex: '',
        mother: '',
        motherIndex: '',
        breedIndex: '',
        inbreed: '',
        remark: '',
        creator: '',
        createDate: '',
        updater: '',
        updateDate: '',
        operator: ''
      },
      pickerOptions: { 
        disabledDate: (time) => {
            var year1=new Date(time).getFullYear();
				    var year2=new Date().getFullYear();
            return time.getTime() > Date.now() || (year2-year1 >= 5);
        }
      },
      houses:{}
    }
  },
  computed: {
    dataRule () {
      return {
        houseId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        earmark: [
          { required: this.earmarkRequired, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        gender: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        sources: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        state: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        birthDate: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        inDate: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        age: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        birthWeight: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        siblings: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        breed: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        strain: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        pedigree: [
          { required: false, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        father: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        fatherIndex: [
          { required: false, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        mother: [
          { required: false, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        motherIndex: [
          { required: false, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        breedIndex: [
          { required: false, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        inbreed: [
          { required: false, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    dataForm: {
      handler(newForm, oldForm) {
        if(newForm.state == "1") {
          this.earmarkRequired = false;
        } else {
          this.earmarkRequired = true;
        }
        //this.$forceUpdate();
      },
      deep: true
    }
  },
  mounted() {
    this.getHouses()
  },
  methods: {
    gridSelect(grid) {
      console.table(grid)
      this.dataForm.grid.row = grid.row
      this.dataForm.grid.column = grid.column
      this.dataForm.grid.name = grid.name
      this.$forceUpdate();
    },
    init () {
      this.visible = true
      let that = this
      this.$nextTick(() => {
        if (!this.dataForm.id) {
          this.$refs['dataForm'].resetFields()
          that.$forceUpdate()
        }
        this.getHouses()
      })
    },
    house_change() {
      let house = this.houses[this.dataForm.houseId]
      this.rows = []
      this.columns = []
      for (let i=0; i<house.rows; ++i) {
        this.rows.push({
          value: i+1,
          label: i+1+'行'
        })
      }
      for (let i=0; i<house.columns; ++i) {
        this.columns.push({
          value: i+1,
          label: i+1+'列'
        })
      }
      this.$forceUpdate()
    },
    getHouses () {
      let that = this;
      this.$http.get(`/basic/house/all`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        res.data.forEach(function(house){
          that.houses[house.id] = house;
        });
        this.house_change()
        this.$forceUpdate()
      }).catch(() => {})
    },
    gridInput() {
      this.$nextTick(() => {
        if(this.dataForm.grid !== null){
          this.dataForm.grid = this.dataForm.grid.replace(/[^\d-]|_/ig,'');
          //this.dataForm.grid = this.dataForm.grid.replace(/[\u4e00-\u9fa5]/g,'')
          this.$forceUpdate();
        }
      })
    },
    inBtnClick () {
      this.visible = false
      this.$emit("uploadModal");
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.dataForm.grid = this.dataForm.grid.row + '-' + this.dataForm.grid.column;
        this.$http[!this.dataForm.id ? 'post' : 'put']('/stock/pig/', this.dataForm).then(({ data: res }) => {
          this.dataForm.grid = {row:'', column:''};
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              if(!this.continues) {
                this.visible = false
              } else {
                for(let key in this.dataForm) {
                  this.dataForm[key] = '';
                }
                this.dataForm.grid = {row:'', column:''};
              }
              
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style scoped>
    .el-input, .el-select {
      width: 180px;
    }

    .el-textarea {
      width: 460px;
    }
</style>
